package com.jinyi.wwdeng.autodialer.manager

import android.app.Activity
import android.app.Dialog
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.core.graphics.drawable.toDrawable
import com.jinyi.wwdeng.autodialer.R
import com.jinyi.wwdeng.autodialer.databinding.DialogLoadingBinding
import java.lang.ref.WeakReference

/**
 * 加载中管理类
 */
class LoadingManager private constructor() {
    companion object {
        @Volatile
        private var instance: LoadingManager? = null

        fun getInstance(): LoadingManager {
            return instance ?: synchronized(this) {
                instance ?: LoadingManager().also { instance = it }
            }
        }
    }

    private var loadingDialog: Dialog? = null
    private var currentActivity: WeakReference<Activity>? = null
    private var isShowing = false

    // 配置参数
    private var defaultMessage = ""
    private var cancelable = false
    private var animationStyle = R.style.LoadingDialogTheme

    /**
     * 初始化配置
     */
    fun initConfig(config: LoadingConfig) {
        this.defaultMessage = config.defaultMessage
        this.cancelable = config.cancelable
        this.animationStyle = config.animationStyle
    }

    /**
     * 显示加载对话框
     */
    fun show(activity: Activity) {
        show(activity, defaultMessage, cancelable)
    }

    /**
     * 显示加载对话框
     */
    fun show(activity: Activity, message: String?) {
        show(activity, message, cancelable)
    }

    /**
     * 显示加载对话框
     */
    fun show(activity: Activity, message: String?, cancelable: Boolean) {
        if (!isActivityValid(activity)) return

        // 先隐藏之前的对话框
        dismiss()

        activity.runOnUiThread {
            try {
                currentActivity = WeakReference(activity)
                createDialog(activity, message, cancelable)

                loadingDialog?.takeIf { !it.isShowing }?.let { dialog ->
                    dialog.show()
                    isShowing = true
                }
            } catch (e: Exception) {
                e.printStackTrace()
                cleanup()
            }
        }
    }

    /**
     * 隐藏加载对话框
     */
    fun dismiss() {
        if (!isShowing || loadingDialog == null) return

        val activity = getCurrentActivity()
        if (!isActivityValid(activity)) {
            cleanup()
            return
        }

        activity?.runOnUiThread {
            try {
                loadingDialog?.takeIf { it.isShowing }?.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                cleanup()
            }
        }
    }

    /**
     * 创建对话框
     */
    private fun createDialog(activity: Activity, message: String?, cancelable: Boolean) {
        try {
            loadingDialog = Dialog(activity, animationStyle).apply {
                val binding = DialogLoadingBinding.inflate(LayoutInflater.from(activity))
                setContentView(binding.root)
                setCancelable(cancelable)
                setCanceledOnTouchOutside(cancelable)

                // 设置内容
                binding.loadingText.text = message ?: defaultMessage

                // 设置窗口属性
                window?.apply {
                    setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
                    setGravity(Gravity.CENTER)
                    attributes = attributes.apply {
                        width = WindowManager.LayoutParams.WRAP_CONTENT
                        height = WindowManager.LayoutParams.WRAP_CONTENT
                        dimAmount = 0.2f // 背景暗淡程度
                    }
                }
                // 设置取消监听
                if (cancelable) {
                    setOnCancelListener { cleanup() }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            cleanup()
        }
    }

    /**
     * 清理资源
     */
    private fun cleanup() {
        try {
            loadingDialog?.dismiss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        loadingDialog = null
        currentActivity = null
        isShowing = false
    }

    /**
     * 获取当前Activity
     */
    private fun getCurrentActivity(): Activity? {
        return currentActivity?.get()
    }

    /**
     * 检查是否正在显示
     */
    fun isShowing(): Boolean {
        return isShowing && loadingDialog?.isShowing == true
    }

    /**
     * 安全显示（自动检查Activity状态）
     */
    fun safeShow(activity: Activity, message: String? = null) {
        if (isActivityValid(activity)) {
            show(activity, message)
        }
    }

    /**
     * 检查Activity是否有效
     */
    private fun isActivityValid(activity: Activity?): Boolean {
        return activity != null && !activity.isFinishing && !activity.isDestroyed
    }

    /**
     * 释放资源（在Application中调用）
     */
    fun release() {
        dismiss()
        instance = null
    }

    data class LoadingConfig(
        var defaultMessage: String = "加载中...",
        var cancelable: Boolean = false,
        var animationStyle: Int = R.style.LoadingDialogTheme,
    ) {
        // 链式调用方法
        fun setDefaultMessage(message: String) = apply { this.defaultMessage = message }
        fun setCancelable(cancelable: Boolean) = apply { this.cancelable = cancelable }
        fun setAnimationStyle(style: Int) = apply { this.animationStyle = style }
    }
}